<?php

namespace addons\yungift\model;

use addons\yungift\library\ModelTrait;
use think\Model;
use traits\model\SoftDelete;

/**
 * 礼品 - 规格
 */
class GiftSpec extends Model
{
    use ModelTrait;
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'yungift_gift_spec';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = 'deleted_at';
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    // 不显示的字段
    protected $hidden = ['deleted_at'];

    protected $resultSetType = 'collection';

    // 自定义初始化
    protected static function init()
    {
        GiftSpec::event('before_write', function ($item) {
            return true;
        });
    }

    public function giftData()
    {
        return $this->belongsTo(GiftMain::class, 'gift_id', 'id');
    }


    // 类型
    const TYPE_1 = 1;
    const TYPE_2 = 2;

    public static function getTypeList()
    {
        return [self::TYPE_1 => __('实物'), self::TYPE_2 => __('虚拟商品')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $optionList = self::getTypeList();

        return $optionList[$data['type']] ?? $data['type'];
    }

    // 获取select列表
    public static function getOptionList($giftId)
    {
        $options = [];
        $dataList = GiftSpec::field(['id', 'name'])->where(['gift_id' => $giftId])->select();
        foreach ($dataList as $item) {
            $options[$item['id']] = $item['name'];
        }

        return $options;
    }
}
